package com.powerbank.financecenter.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.powerbank.financecenter.entity.TransactionRecord;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.util.List;

/**
 * 交易记录Mapper接口
 */
@Mapper
public interface TransactionRecordMapper extends BaseMapper<TransactionRecord> {

    /**
     * 根据交易号查询交易记录
     */
    @Select("SELECT * FROM transaction_record WHERE transaction_no = #{transactionNo} AND deleted = 0")
    TransactionRecord findByTransactionNo(@Param("transactionNo") String transactionNo);

    /**
     * 根据用户ID查询交易记录
     */
    @Select("SELECT * FROM transaction_record WHERE user_id = #{userId} AND deleted = 0 ORDER BY created_time DESC")
    List<TransactionRecord> findByUserId(@Param("userId") Long userId);

    /**
     * 根据订单号查询交易记录
     */
    @Select("SELECT * FROM transaction_record WHERE order_no = #{orderNo} AND deleted = 0")
    List<TransactionRecord> findByOrderNo(@Param("orderNo") String orderNo);

    /**
     * 根据交易类型和状态查询交易记录
     */
    @Select("SELECT * FROM transaction_record WHERE transaction_type = #{transactionType} AND status = #{status} AND deleted = 0")
    List<TransactionRecord> findByTypeAndStatus(@Param("transactionType") String transactionType, @Param("status") String status);

    /**
     * 统计用户交易总额
     */
    @Select("SELECT SUM(amount) FROM transaction_record WHERE user_id = #{userId} AND direction = 'IN' AND status = 'SUCCESS' AND deleted = 0")
    Double sumIncomeByUserId(@Param("userId") Long userId);

    /**
     * 统计用户支出总额
     */
    @Select("SELECT SUM(amount) FROM transaction_record WHERE user_id = #{userId} AND direction = 'OUT' AND status = 'SUCCESS' AND deleted = 0")
    Double sumExpenseByUserId(@Param("userId") Long userId);
}